<template>
  <div class="user">
    <el-row>
      <el-col :span="20">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="影院名称">
            <el-input
              v-model="formInline.desc"
              placeholder="影院名称"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="queryPanel()">查询</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="4" style="text-align: right">
        <el-button
          type="primary"
          icon="el-icon-circle-plus-outline"
          @click="dialogVisible = true"
        >添加影院</el-button>
      </el-col>
    </el-row>
    <div class="table">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column type="index" width="50" />
        <el-table-column prop="cinemaName" label="影院名称" width="220" />
        <el-table-column prop="address" label="影院地址" />
        <el-table-column prop="phone" label="影院电话" width="180" />
        <el-table-column prop="date" label="营业时间" width="200">
          <template slot-scope="scope">
            <span>{{ scope.row.date.join("-") }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="cinemaType" label="拥有影厅类型" width="300">
          <template slot-scope="scope">
            <el-tag v-for="(item, i) in scope.row.cinemaType" :key="i">{{
              item
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140">
          <template slot-scope="scope">
            <el-link
              v-if="curRole === 'admin'"
              type="primary"
              :underline="false"
              style="margin-right: 15px"
              @click="edit(scope.row.id)"
            >
              编辑
            </el-link>
            <el-link
              v-if="curRole != 'admin'"
              type="primary"
              :underline="false"
              style="margin-right: 15px"
              @click="detail(scope.row.id)"
            >
              详情
            </el-link>
            <el-link
              v-if="curRole === 'admin'"
              type="danger"
              :underline="false"
              @click="remove(scope.row.id)"
            >
              删除
            </el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog
      title="上架电影"
      :visible.sync="dialogVisible"
      width="60%"
      top="8vh"
      :before-close="handleClose"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
    >
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="90px"
        class="demo-ruleForm"
        label-position="left"
        :disabled="disabled"
      >
        <el-form-item label="影院名称" prop="cinemaName">
          <el-input v-model="ruleForm.cinemaName" />
        </el-form-item>
        <el-form-item label="影院地址" prop="address">
          <el-input v-model="ruleForm.address" />
        </el-form-item>
        <el-form-item label="影院电话" prop="phone">
          <el-input v-model="ruleForm.phone" />
        </el-form-item>
        <el-form-item label="营业时间" prop="date">
          <el-time-picker
            v-model="ruleForm.date"
            is-range
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            placeholder="选择时间范围"
            value-format="HH:mm"
          />
        </el-form-item>
        <el-form-item label="影厅类型" prop="cinemaType">
          <el-tag
            v-for="tag in ruleForm.cinemaType"
            :key="tag"
            closable
            :disable-transitions="false"
            @close="removeTag(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="inputVisible"
            ref="saveTagInput"
            v-model="inputValue"
            class="input-new-tag"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button
            v-else
            class="button-new-tag"
            size="small"
            @click="showInput"
          >+ 新增类型</el-button>
        </el-form-item>
        <el-form-item label="影院照片">
          <el-upload
            class="avatar-uploader"
            action="http://192.168.4.105:7777/e5/file/upload"
            :show-file-list="false"
            :on-change="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="ruleForm.cinemaImg"
              :src="ruleForm.cinemaImg"
              class="avatar"
            >
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          v-if="disabled"
          type="primary"
          @click="close()"
        >关 闭</el-button>
        <el-button v-if="!disabled" @click="close()">取 消</el-button>
        <el-button
          v-if="!disabled"
          type="primary"
          @click="submitForm('ruleForm')"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Cinema',
  data() {
    return {
      curRole: '',
      inputVisible: false,
      inputValue: '',
      disabled: false,
      isEdit: false,
      dialogVisible: false,
      ruleForm: {
        id: new Date().getTime(),
        cinemaName: '',
        address: '',
        phone: '',
        date: ['10:30', '23:00'],
        cinemaType: ['4D厅', '巨幕厅'],
        cinemaImg: ''
      },
      rules: {
        cinemaName: [
          { required: true, message: '请输入影院名称', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入影院地址', trigger: 'blur' }
        ],
        phone: [{ required: true, message: '请输入影院电话', trigger: 'blur' }],
        date: [{ required: true, message: '请选择营业时间', trigger: 'blur' }]
      },
      formInline: {
        desc: ''
      },
      cinemas: [
        {
          id: 1,
          cinemaName: '万达影城（高新区店）',
          address: '地址：高新区乌龙江南大道69号19号楼万达广场4层',
          phone: '020-888888888',
          date: ['10:30', '23:00'],
          cinemaType: [
            'IMAX厅',
            '杜比全景声厅',
            'DTS:X 临境音厅',
            '4D厅',
            '儿童厅',
            '巨幕厅'
          ],
          cinemaImg: require('@/icons/image/cinema/wd.jpg')
        },
        {
          id: 2,
          cinemaName: '中影星美国际影城（闽侯店）',
          address: '闽侯县甘蔗街道昙石山大道北侧万家广场7#楼第三、四层',
          phone: '0591-62085888',
          date: ['10:30', '23:00'],
          cinemaType: ['IMAX厅', '杜比全景声厅', '3D厅', '4D厅', '巨幕厅'],
          cinemaImg: require('@/icons/image/cinema/wd.jpg')
        }
      ],
      tableData: []
    }
  },
  async created() {
    const cinemaArr = await this.$localStorage.getItem('allCinemas')
    if (!cinemaArr) {
      await this.$localStorage.setItem('allCinemas', this.cinemas)
    }
    this.curRole = await this.$localStorage.getItem('curRole')
    this.getCinemaList()
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          let cinemaArr =
            (await this.$localStorage.getItem('allCinemas')) || []
          if (this.isEdit) {
            cinemaArr = cinemaArr.map((item) => {
              if (item.id === this.ruleForm.id) {
                item = this.ruleForm
              }
              return item
            })
            await this.$localStorage.setItem('allCinemas', cinemaArr)
            this.$message({
              type: 'success',
              message: '修改成功'
            })
          } else {
            cinemaArr.unshift(this.ruleForm)
            await this.$localStorage.setItem('allCinemas', cinemaArr)
            this.$message({
              type: 'success',
              message: '添加成功'
            })
          }

          this.close()
          this.getCinemaList()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleAvatarSuccess(file) {
      // this.ruleForm.cinemaImg = URL.createObjectURL(file.raw);
      const fd = new FileReader()
      fd.readAsDataURL(file.raw)
      // 将文件转化为base64格式写入json文件
      fd.onload = () => {
        const keyString = fd.result
          .toString()
          .replace('data:application/x-pkcs12;base64,', '')
        // console.log("keyString", keyString)
        this.ruleForm.cinemaImg = keyString
      }
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    },

    close() {
      this.ruleForm = {
        id: new Date().getTime(),
        cinemaName: '',
        address: '',
        phone: '',
        date: ['10:30', '23:00'],
        cinemaType: ['4D厅', '巨幕厅'],
        cinemaImg: ''
      }
      this.dialogVisible = false
      this.disabled = false
      this.isEdit = false
    },
    add() {
      this.dialogVisible = true
    },
    // 编辑
    async edit(id) {
      const cinemaArr = (await this.$localStorage.getItem('allCinemas')) || []

      const curVal = cinemaArr.find((item) => item.id === id)
      this.ruleForm = curVal

      this.isEdit = true
      this.dialogVisible = true
    },
    async detail(id) {
      const cinemaArr = (await this.$localStorage.getItem('allCinemas')) || []

      const curVal = cinemaArr.find((item) => item.id === id)
      this.ruleForm = curVal

      this.disabled = true
      this.dialogVisible = true
    },
    async remove(id) {
      let cinemaArr = (await this.$localStorage.getItem('allCinemas')) || []
      this.$confirm('此操作将删除该电影, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          cinemaArr = cinemaArr.filter((item) => {
            return item.id !== id
          })
          await this.$localStorage.setItem('allCinemas', cinemaArr)
          this.$message({
            type: 'success',
            message: '删除成功'
          })
          this.getCinemaList()
        })
        .catch(() => {})
    },
    handleClose(done) {
      this.close()
    },

    async getCinemaList() {
      const cinemaArr = (await this.$localStorage.getItem('allCinemas')) || []
      this.tableData = cinemaArr
    },

    // 删除标签
    removeTag(tag) {
      this.ruleForm.cinemaType.splice(this.ruleForm.cinemaType.indexOf(tag), 1)
    },

    showInput() {
      this.inputVisible = true
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.ruleForm.cinemaType.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    // 查询
    async queryPanel() {
      const cinemas = await this.$localStorage.getItem('allCinemas')

      const { desc } = this.formInline

      const newCinemas = cinemas.filter((item) => {
        if (item.cinemaName.includes(desc)) {
          return item
        }
      })

      this.tableData = newCinemas
      // console.log(movieName, movieType, hotnew);
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar-uploader ::v-deep .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
}
.avatar {
  width: 148px;
  height: 148px;
  object-fit: cover;
  display: block;
}

.user {
  padding: 20px 100px;
  .table {
  }
  .el-tag {
    margin-right: 10px;
    margin-bottom: 5px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
}
</style>

